import React from 'react';
import {
    Button,
    Text,
    View,
    Image,
    StyleSheet,
    Dimensions,
    StatusBar,
    ActivityIndicator,
    FlatList,
    ScrollView,
    RefreshControl,
    Animated,
    SectionList,
    TouchableOpacity,
    Modal,
    PermissionsAndroid,
    ToastAndroid

} from 'react-native';

import { Card } from 'react-native-shadow-cards';
import QRCode from 'react-native-qrcode-svg';
import ViewShot from "react-native-view-shot";
import Styles from './Styles';
import CameraRoll from "@react-native-community/cameraroll";
import Utils from "../../utils/Utils";
const { width, height } = Dimensions.get('window');


// 初始化总数据

export default class Site extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            site: {},
            message: '',
            toastModelVisible: false
        };

    }
    static navigationOptions = {
        title: '',
        //header: null,  //隐藏顶部导航栏
        //tabBarVisible: false, // 隐藏底部导航栏
        headerStyle: {
            backgroundColor: 'transparent',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
            fontWeight: 'bold',
        },
    }
    componentWillMount() {
        //组件将要被加载到视图之前调用
        const { navigation } = this.props;
        const site = navigation.getParam("site")
        const logo = navigation.getParam("logo");
        this.setState({
            site: site,
            logo: logo
        });
    }
    componentDidMount() {
        // 在调用了render方法，组件加载成功并被成功渲染出来之后，所要执行的后续操作，一般都会在这个函数中进行，比如经常要面对的网络请求等加载数据操作
        // *** 因为UI已经成功渲染，而且这里面是异步的，所以放在这个函数进行数据的请求等复杂的操作，不会出现UI错误**
        this.requestMultiplePermission();

    }
    async requestMultiplePermission() {
        try {
            const permissions = [                
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                PermissionsAndroid.PERMISSIONS.CAMERA
            ]
            //返回得是对象类型
            const granteds = await PermissionsAndroid.requestMultiple(permissions)
            var data = "是否同意地址权限: "
            if (granteds["android.permission.ACCESS_FINE_LOCATION"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }
            data = data+"是否同意相机权限: "
            if (granteds["android.permission.CAMERA"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }
            data = data+"是否同意存储权限: "
            if (granteds["android.permission.WRITE_EXTERNAL_STORAGE"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }
            //this.show(data)
        } catch (err) {
            //this.show(err.toString())
        }
    }
    show(data) {
        ToastAndroid.show(data,ToastAndroid.SHORT)
    }
    takePhoto() {
        this.refs.location.capture().then(uri => {
            this.saveImg(uri);
        });
    }
    //保存图片
    saveImg(img) {
        var promise = CameraRoll.saveToCameraRoll(img);
        promise.then((result)=> {
            this.do_toast('二维码保存成功',500);
        }).catch((error)=> {
            alert(error);
        });
    }

    _do_change_type = () => {
        let type = this.state.type;
        if (type == 1) {
            this.setState({
                type: 2
            });
        } else {
            this.setState({
                type: 1
            });
        }
    }
    do_toast = (str, time) => {
        this.setState({
            message: str,
            toastModelVisible: true
        });
        setTimeout(() => {
            this.setState({
                message: '',
                toastModelVisible: false
            });
        }, time);
    }
    toast = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={this.state.toastModelVisible}
                onRequestClose={() => {
                    this.setState({
                        toastModelVisible: false
                    });
                }}
            >
                <View style={{ flexDirection: 'row', justifyContent: 'center', position: 'absolute', bottom: 100, width: width }}>
                    <Text style={{ backgroundColor: 'rgba(0,0,0,0.5)', color: '#ffffff', borderRadius: 10, height: 40, lineHeight: 40, paddingLeft: 20, paddingRight: 20 }}>{this.state.message}</Text>
                </View>
            </Modal>
        );
    }
    render() {
        let site = this.state.site;
        let logo = this.state.logo;
        let shopaddress = site.shopaddress;
        if(shopaddress.length>9){
            shopaddress=Utils.plusXing(shopaddress, 9, shopaddress.length)
        }
        return (
            <View style={Styles.container}>
                <StatusBar translucent={true} backgroundColor="transparent" />
                <Image resizeMode="cover" style={Styles.qrcode_bj} source={require('../../image/js_img_qrcode_bj.png')} />
                <View>
                    <Card style={Styles.siteContainer}>
                        <View>
                            <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', marginTop: -50 }}>
                                <Image resizeMode="cover" style={Styles.defoult_logo} source={{ uri: logo }} />
                                <Text style={{ textAlign: 'center', marginTop: 18 }}>{site.shopname}</Text>
                            </View>

                            <View style={Styles.hp_item}>
                                <Image style={Styles.dp_icon} source={require('../../image/js_img_dp_icon.png')} />
                                <Text style={{ color: '#686868' }}>{site.phone}</Text>
                            </View>
                            <View style={Styles.hp_item}>
                                <Image resizeMode="cover" style={Styles.dp_icon} source={require('../../image/js_img_mz_icon.png')} />
                                <Text style={{ color: '#686868' }}>{shopaddress}</Text>
                            </View>
                            <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', marginTop: 60 }}>
                                <ViewShot ref='location' style={Styles.QRcode_bg}>
                                    <QRCode
                                        value={site.appurl}
                                        logo={{ uri: logo }}
                                        logoSize={20}
                                        //logoBackgroundColor='transparent'
                                        logoMargin={2}
                                        size={100}
                                    />
                                </ViewShot>
                                <Text style={{ color: '#686868', marginTop: 20 }}>扫描二维码，下载店主APP</Text>
                            </View>
                            <View style={{ flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', marginTop: 35 }}>
                                <TouchableOpacity onPress={() => this.takePhoto()}>
                                    <View style={Styles.but2}>
                                        <Text style={{ color: '#ffffff', fontSize: 16, textAlign: 'center' }}>保存二维码</Text>
                                    </View>
                                </TouchableOpacity>
                            </View> 
                        </View>
                    </Card>
                </View>
                {this.toast()}
            </View>
        )
    }
}

